package biz.datalk.industrialland.admin.modules.sync.controller;

import biz.datalk.commons.utils.ip.IPUtil;
import biz.datalk.industrialland.admin.modules.common.controller.GitVersionController;
import biz.datalk.industrialland.admin.modules.sync.service.ISyncService;
import biz.datalk.industrialland.common.result.UnifyResult;
import biz.datalk.industrialland.common.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 同步接口
 *
 * @author tarofang@163.com
 * @date 2024-01-18
 */
@RestController
@RequestMapping("/api/sync")
public class SyncController {

    private final RedisUtil redisUtil;
    private final ISyncService syncService;

    @Autowired
    public SyncController(RedisUtil redisUtil, ISyncService syncService) {
        this.redisUtil = redisUtil;
        this.syncService = syncService;
    }

    /**
     * demo
     *
     * @param sign 接口调用标识
     *
     * @return 出参
     *
     * @author tarofang@163.com
     * @date 2024年02月19日
     */
    @RequestMapping("/demo")
    public UnifyResult demo(@RequestParam(value = "sign", required = false) String sign, HttpServletRequest request) {
        checkSignAndRemoteIp(sign, request, "demo");
        // TODO Demo sync
        return UnifyResult.success();
    }


    private void checkSignAndRemoteIp(String sign, HttpServletRequest request, String apiType) {
        Assert.hasText(sign, "参数错误");
        Assert.hasText(apiType, "未知的接口类型");

        // 校验 IP
        String remoteIp = IPUtil.getIpAddress(request);
        String chkIp = StringUtils.isBlank(remoteIp) ? StringUtils.EMPTY : GitVersionController.SEPARATOR_SEMICOLON.concat(remoteIp).concat(GitVersionController.SEPARATOR_SEMICOLON);
        String cacheAllowIpsKey = "api.sign:".concat(apiType).concat(".allow.ips");
        String allowIps = redisUtil.getStr(cacheAllowIpsKey, ";127.0.0.1;localhost;");
        Assert.isTrue(StringUtils.contains(allowIps, chkIp), "无权限访问");

        // 校验 sign
        String cacheSignKey = "api.sign:".concat(apiType);
        String cacheSign = redisUtil.getStr(cacheSignKey);
        Assert.isTrue(StringUtils.equals(sign, cacheSign), "您没有权限访问");
    }

}
